<template>
  <div class="app-wrapper">
    <headerTitle
      :titleList="titleList"
      :hideButton="false"
      :btnTitle="'新增菜单'"
      icon="iconfont btn_enterprise(3) icon-btn_enterprise3"
      @handelClick="() => add()"
    />
    <div class="app-container">
      <div class="containerMain">
        <el-tree
          style="width:80%"
          :data="treeData"
          node-key="id"
          default-expand-all
          :props="defaultProps"
          :expand-on-click-node="false"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ data.name }}</span>
            <span>
              <el-button
                v-show="!data.child[0]"
                type="text"
                size="mini"
                class="el-icon-delete"
                @click="() => del(data)"
              />
              <el-button
                type="text"
                size="mini"
                class="el-icon-edit"
                @click="() => update(data)"
              />
            </span>
          </span>
        </el-tree>
      </div>
      <el-dialog :title="activeTitle" :visible.sync="dialogFormVisible">
        <el-form ref="ruleForm" :model="form" :rules="rules">
          <el-form-item label="类型" :label-width="formLabelWidth">
            <el-radio-group v-model="form.type" :disabled="disButton">
              <el-radio :label="1">目录</el-radio>
              <el-radio :label="2">菜单</el-radio>
              <el-radio :label="3">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="归属类型" :label-width="formLabelWidth">
            <el-radio-group v-model="form.entNum" :disabled="disButton" @change="changeTreeData(userType,form.entNum)">
              <el-radio label="super">super</el-radio>
              <el-radio label="0">企业</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="父节点"
            :label-width="formLabelWidth"
            v-show="form.entNum!=''"
            prop="parentId"
          >
            <el-cascader
              :disabled="disButton"
              :key="keyValue"
              :options="treeData1"
              v-model="form.parentId"
              size="mini"
              :props="{
                value: 'id',
                label: 'name',
                children: 'child',
                checkStrictly: true,
                emitPath: false
              }"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
            <el-input
              v-model="form.name"
              size="mini"
              clearable
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="图标" :label-width="formLabelWidth" prop="icon">
            <el-input
              v-model="form.icon"
              size="mini"
              clearable
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item
            v-if="form.type == 2 || form.type == 3"
            :label="form.type == 2 ? '地址' : form.type == 3 ? '按钮标识' : ''"
            :label-width="formLabelWidth"
            prop="url"
          >
            <el-input
              v-model="form.url"
              size="mini"
              clearable
              autocomplete="off"
            />
          </el-form-item>

          <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
            <el-input
              v-model="form.sort"
              size="mini"
              clearable
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogFormVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" size="small" @click="save">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import HeaderTitle from "@/components/Headertitle/index";
import { getInfo } from "@/api/user"
import { fetchmenuTree } from "@/api/systemapi/auth";
import { fetchMenuAdd, fetchDel,fetchUpdate } from "@/api/systemapi/menu";

export default {
  components: {
    headerTitle: HeaderTitle
  },
  data() {
    return {
      keyValue:0,
      userType: 0,
      titleList: [{ title: "菜单管理" }],
      treeData: null,
      list: null,
      menuList: null,
      listLoading: true,
      defaultProps: {
        children: "child",
        label: "name",
        id: "id"
      },
      disButton: false,
      activeTitle: "新增菜单", // 新增编辑菜单模态框标题
      dialogFormVisible: false, // 模态框
      formLabelWidth: "100px",
      treeData1: [],
      form: {
        name: "",
        entNum:"",
        parentId: "",
        type: 2,
        icon: "",
        url: "",
        sort: ""
      },
      rules: {
        parentId: [
          { required: true, message: "请选择父级节点", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入菜单名称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        url: [
          {
            required: true,
            validator: (rule, value,callback) => {
              if (!value&&this.form.type==2) {
                callback(new Error("请输入菜单地址"));
              }
              if (!value&&this.form.type==3) {
                callback(new Error("请输入按钮标识"));
              }
              callback();
            },
            // message: this.form.type == 2 ? "请输入菜单地址" : "请输入按钮标识",
            trigger: "blur"
          }
        ],
        icon: [
          { min: 0, max: 40, message: "长度在最多 40 个字符", trigger: "blur" }
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }]
      }
    };
  },

  watch: {
    // "form.type"(newval, oldval) {
    //   console.log(newval, oldval);
    //   if (this.$refs["ruleForm"]) {
    //     this.$refs["ruleForm"].resetFields();
    //   }
    //   if (newval == 3 || newval == 4) {
    //     this.$refs["ruleForm"].resetFields();
    //   }
    // }
  treeData(newVal) {
    console.log(123123);
    this.keyValue++ //只要监听到数据源发生变化 ，改变keyValue的值，达到重新渲染的效果
  }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      getInfo().then((res)=>{
        res.data.entNum === "super"?this.userType = 3:this.userType = 2
        this.fetchTreeData(this.userType);
      })
    },
    fetchTreeData(type) {
      this.listLoading = true;
      fetchmenuTree( {
        disable: false,
        type:type,
      }).then(response => {
        // this.menulist = response.data;
        this.treeData = this.filterData(response.data);
        console.log(1,this.treeData);
        console.log(1213123,response.data);
        this.listLoading = false;
      });
    },
    changeTreeData(type,entNum) {
      this.listLoading = true;
      fetchmenuTree( {
        disable: false,
        type:type,
        entNum: entNum
      }).then(response => {
        // this.menulist = response.data;
        this.treeData1 = this.filterData(response.data);
      });
    },
    filterData(data) {
      for (let i = 0; i < data.length; i++) {
        console.log(data[i].child, "data[i].child")
        if (data[i].child == null) {
          data[i].child = undefined;
        } else {
          this.filterData(data[i].child);
        }
      }
      return data;
    },
    add() {
      this.disButton = false;
      this.form = {
        name: "",
        parentId: "",
        entNum:"",
        type: 2,
        icon: "",
        url: "",
        sort: ""
      };
      // this.resetFileds();
      this.dialogFormVisible = true;
      this.activeTitle = "新增菜单";
    },
    // 删除
    // 删除
    del(data) {
      console.log(data, "节点");
      this.$confirm("是否确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          fetchDel({
            id: data.id
          }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success"
              });
              this.dialogFormVisible = false;
              this.fetchTreeData(this.userType);
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 新增
    update(data) {
      this.disButton = true;
      if(data.entNum!="super"){
        data.entNum="0"
      }
      this.form = {
        ...data
      };
console.log(this.form)
      this.dialogFormVisible = true;
      // this.resetFileds();
      this.activeTitle = "编辑菜单";

    },
    // 保存
    save() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.disButton) {
            console.log(this.form);
            fetchUpdate(this.form).then(response => {
              if (response.code === 0) {
                this.$message({
                  message: "编辑菜单成功",
                  type: "success"
                });
                this.dialogFormVisible = false;
                this.fetchTreeData(this.userType);
              } else {
                this.$message({
                  message: response.msg,
                  type: "error"
                });
              }
            });
          } else {
            fetchMenuAdd(this.form).then(response => {
              if (response.code === 0) {
                this.$message({
                  message: "新增菜单成功",
                  type: "success"
                });
                this.dialogFormVisible = false;
                this.fetchTreeData(this.userType);
              } else {
                this.$message({
                  message: response.msg,
                  type: "error"
                });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // resetFileds() {
    //   // 重置校验
    //   if (this.$refs["ruleForm"]) {
    //     this.$refs["ruleForm"].resetFields();
    //   }
    // }
  }
};
</script>
<style lang="scss" scoped>
.containerMain {
  padding-top: 10px;
  flex-direction: row;
  justify-content: space-around;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
